<template>
  <a-modal
  id="modalPopup"
    :title="title"
    :width="modalWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin tip="Loading..." :spinning="false">
      <a-row :gutter="18">
        <a-col :span="24">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchByquery">
              <a-row :gutter="24" v-if="queryInfo && queryInfo.length>0">
                <template v-for="(item,index) in queryInfo">
                  <template v-if=" item.hidden==='1' ">
                    <a-col
                      v-if="item.view=='datetime'"
                      :md="12"
                      :sm="16"
                      :key=" 'query'+index "
                      v-show="toggleSearchStatus"
                    >
                      <online-query-form-item
                        :queryParam="queryParam"
                        :item="item"
                        :dictOptions="dictOptions"
                      ></online-query-form-item>
                    </a-col>
                    <a-col
                      v-else
                      :md="6"
                      :sm="8"
                      :key=" 'query'+index "
                      v-show="toggleSearchStatus"
                    >
                      <online-query-form-item
                        :queryParam="queryParam"
                        :item="item"
                        :dictOptions="dictOptions"
                      ></online-query-form-item>
                    </a-col>
                  </template>
                  <template v-else>
                    <a-col v-if="item.view=='datetime'" :md="12" :sm="16" :key=" 'query'+index ">
                      <online-query-form-item
                        :queryParam="queryParam"
                        :item="item"
                        :dictOptions="dictOptions"
                      ></online-query-form-item>
                    </a-col>
                    <a-col v-else :md="6" :sm="8" :key=" 'query'+index ">
                      <online-query-form-item
                        :queryParam="queryParam"
                        :item="item"
                        :dictOptions="dictOptions"
                      ></online-query-form-item>
                    </a-col>
                  </template>
                </template>

                <a-col :md="6" :sm="8">
                  <span
                    style="float: left;overflow: hidden;"
                    class="table-page-search-submitButtons"
                  >
                    <a-button type="primary" @click="searchByquery" icon="search">查询</a-button>
                    <a-button
                      type="primary"
                      @click="searchReset"
                      icon="reload"
                      style="margin-left: 8px"
                    >重置</a-button>
                    <a v-if="queryInfo.length > 2" @click="handleToggleSearch" style="margin-left: 8px">
                      {{ toggleSearchStatus ? '收起' : '展开' }}
                      <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                    </a>

                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>

          <a-table
          class="popupTable"
            ref="table"
            size="middle"
            bordered
            :rowKey="combineRowKey"
            :columns="columns"
            :dataSource="dataSource"
            :scroll="scroll"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange"
            style="height: 300px"
            :customRow="clickThenCheck"
          ></a-table>
        </a-col>
      </a-row>
    </a-spin>
  </a-modal>
</template>

<script>
function controltype() {}
import { queryDepartTreeList } from '@/api/api'
import { getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/noLoadListMinXin'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import {filterObj} from '@/utils/util';

export default {
  name: 'JSelectDepartModal',
  props: ['modalWidth', 'multi', 'rootOpened', 'departId', 'code', 'field', 'fieldName'],
  mixins: [JeecgListMixin],
  data() {
    return {
      title: '',
      loading: false,
      scroll: { x: false,y:320 },
      queryInfo: [],
      dictOptions: {},
      // 表头
      columns: [],
      //数据集
      dataSource: [],
      // 选择器
      // selectedRowKeys: [],
      // selectionRows: [],
       /* 排序参数 */
      isorter:{
        column: 'createTime',
        order: 'desc',
      },
      ipagination: {
        pageSize: 10
      },
      url: {
        columns: '/online/cgreport/api/getRpColumns/' + this.code,
        list: '/online/cgreport/api/getData/',
        slist: '/online/cgreport/api/getQueryInfo/'
      },
      dataSource: [],
      visible: false,
      confirmLoading: false,
      treeData: [],
      selectedRowKeys: [],
      selectionRows: [],
      star: []
      // autoExpandParent:true,
      // expandedKeys:[],
      // dataList:[],
      // searchValue:""
    }
  },
  created() {
    this.loadColumn()
  },
  watch: {
    departId() {
      //this.initDepartComponent()
    },
    code() {
      this.loadData(1)
    },
    visible: {
      handler() {
        if (this.departId) {
          //alert(2)
          //this.selectedRowKeys = this.departId.split(',')

          this.selectedRowKeys = []
        } else {
          this.selectedRowKeys = []
        }
      }
    }
  },
  methods: {
   

    handleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        // if (Object.keys(sorter).length > 0) {
        //   this.sorter.column = sorter.field
        //   this.sorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
        // } else {
        //   this.sorter.column = null
        //   this.sorter.order = null
        // }
        this.ipagination = pagination
        this.loadData()
      },

    searchByquery() {
      this.loadData(1)
    },
    searchReset() {
      this.queryParam = {}
      this.loadData(1)
    },
    initQueryInfo() {
      getAction(`${this.url.slist}${this.cgRpConfigId}`).then(res => {
        //console.log('--onlineList-获取查询条件配置', res)
        if (res.success) {
          let info = res.result
          this.star = []
          for (var x in info) {
            if (info[x].view === 'string') {
              this.star.push(info[x].field)
            }
          }
          this.queryInfo = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
        this.onClearSelected();
      }

      let star = this.star
      let cgRpConfigId = this.cgRpConfigId
      let url = this.url.list + cgRpConfigId
      let params = this.getQueryParams() //查询条件

      //顶部搜索如果是input则需要模糊搜索添加*
      for (var x = 0; x < star.length; x++) {
        if (params[star[x]] != undefined) {
          params[star[x]] = params[star[x]] + '*'
        }
      }

      //传值参数名与参数值一一对应

      var paraName = this.fieldName.split(',')
      var paraVal = this.field
      //console.log(paraName)
      for (var i = 0; i < paraName.length; i++) {
        // params['self_'+paraName[i]] = paraVal[i]
        params[paraName[i]] = paraVal[i]
      }
      //删除不需参数
      delete params.column
      delete params.field
      // params[paraName[0]] = paraVal[0]
      // params[paraName[1]] = paraVal[1]
      this.loading = true
      //console.log(params)
      getAction(url, params).then(res => {
        if (res.success) {
          this.onClearSelected();
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
          //alert(res.result.total)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    loadColumn() {
      if (!this.url.columns) {
        this.$message.error('请设置url.columns属性!')
        return
      }
      var params = {}
      getAction(this.url.columns, params).then(res => {
        if (res.success) {
          let { data, columns, cgreportHeadName, dictOptions, fieldHrefSlots } = res.result
          let columnWidth = 230
          this.dictOptions = dictOptions
          //this.columns = res.result.columns
          
         
          //   this.dataSource = res.result.records;
          //   this.ipagination.total = res.result.total;
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].customRender) {
              let field_name = columns[a].customRender
              columns[a].customRender = t => (t ? filterMultiDictText(this.dictOptions[field_name], t + '') : t)
            }
            columns.width = columnWidth;
            columns[a].align = 'left';
            columns[a].ellipsis = true;
          }

          this.scroll.x = columns.length * columnWidth
          this.columns = [...columns]
          this.cgRpConfigId = res.result.cgRpConfigId
          this.title = res.result.cgRpConfigName
          // if (data) {
          //     this.pagination.total = Number(data.total)
          //     this.dataSource = data.records
          //   } else {
          //     this.pagination.total = 0
          //     this.dataSource = []
          // }




        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
        this.loadData(1)
        this.initQueryInfo()
      })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.disableSubmit = false
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    show() {
      this.visible = true
      this.loadColumn(1)
      this.selectionRows = []
      this.selectedRowKeys = []
      this.queryParam = {}
      this.ipagination.pageSize=10
    },
    handleSubmit() {
      let multi = this.multi
      //console.log(this.selectedRowKeys.length)
      if (multi == true) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！')
          return
        } else {
          this.$emit('ok', this.selectionRows, this.selectedRowKeys.join(','))
        }
      } else {
        if (this.selectedRowKeys.length <= 0 || this.selectedRowKeys.length > 1) {
          this.$message.warning('单选，请选择一条记录！')
          return
        } else {
          this.$emit('ok', this.selectionRows, this.selectedRowKeys.join(','))
        }
      }

      this.handleClear()
    },
    handleClear() {
      this.visible = false
      this.selectedRowKeys = []
    },
    combineRowKey(record) {
      let res = "";
      Object.keys(record).forEach((key) => {
        res += record[key];
      });
      if (res.length > 50) {
        res = res.substring(0, 50);
      }
      return res;
    },
    clickThenCheck(record) {
      return {
        on: {
          click: () => {
            let rowKey = this.combineRowKey(record);
            if (
              !this.selectedRowKeys ||
              this.selectedRowKeys.length == 0
            ) {
              let arr1 = [],
                arr2 = [];
              arr1.push(record);
              arr2.push(rowKey);
              this.selectedRowKeys = arr2;
              this.selectionRows = arr1;
            } else {
              if (this.selectedRowKeys.indexOf(rowKey) < 0) {
                this.selectedRowKeys.push(rowKey);
                this.selectionRows.push(record);
              } else {
                let rowKey_index = this.selectedRowKeys.indexOf(rowKey);
                this.selectedRowKeys.splice(rowKey_index, 1);
                this.selectionRows.splice(rowKey_index, 1);
              }
            }
          },
        },
      };
    }
  }
}
</script>

<style>
.popupTable .ant-table-scroll .ant-table-body{
  height: 320px;
  padding-bottom: 6px
}
 #modalPopup .ant-modal-content .ant-modal-body{
  padding:6px 24px;
}
</style>